package com.example.myapplication;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.InputType;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.res.ResourcesCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.example.myapplication.data.CaptchaImageData;
import com.example.myapplication.data.LoginData;
import com.example.myapplication.post.LoginPost;
import com.example.mylibrary.utils.AESTool;
import com.example.mylibrary.utils.Base64ToBitmapConverter;
import com.example.mylibrary.utils.DisplayUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class MainActivity extends AppCompatActivity {
    private Boolean isShowPassword=false;
    private CheckBox checkBox;
    private Button button;
    private EditText editAccount;
    private ImageView imgPassword;
    private EditText editPassword;
    private EditText editCode;
    private ImageView imageCode;
    private LoginPost loginPost=new LoginPost();

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        EventBus.getDefault().register(this);
        imgPassword= findViewById(R.id.isShowPassword);
        editPassword=findViewById(R.id.editPassword);
        editAccount=findViewById(R.id.editAccount);
        editCode=findViewById(R.id.editCode);
        imageCode=findViewById(R.id.imageCode);
        imgPassword.setOnClickListener((v)->{
            if (!isShowPassword){
                editPassword.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
                imgPassword.setImageDrawable(ResourcesCompat.getDrawable(getResources(),R.mipmap.show_password,null));
            }else {
                editPassword.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_PASSWORD);
                imgPassword.setImageDrawable(ResourcesCompat.getDrawable(getResources(),R.mipmap.hide_password,null));
            }
            isShowPassword=!isShowPassword;
        });
        button = findViewById(R.id.btLogin);
        checkBox=findViewById(R.id.rememberPs);
        button.setOnClickListener((v)->{
            String account = editAccount.getText().toString();
            String password = editPassword.getText().toString();
            new Thread(()->{
                MyHttpConnection httpConnection=new MyHttpConnection();
                loginPost.setCode(editCode.getText().toString());
                loginPost.setUsername(account);
                loginPost.setPassword(password);
                String login = httpConnection.doPost("http://10.0.2.2:8080/login", (JSONObject) JSON.toJSON(loginPost));
                JSONObject jsonObject = JSONObject.parseObject(login);
                LoginData loginData=new LoginData();
                loginData.setCode(jsonObject.getIntValue("code"));
                loginData.setMsg(jsonObject.getString("msg"));
                loginData.setToken(jsonObject.getString("token"));
                if (loginData.getCode()==200){
                    Intent intent=new Intent(MainActivity.this,BallActivity.class);
                    if (checkBox.isChecked()){
                        // 记录登录状态
                        SharedPreferences myshare = getSharedPreferences("myshare", MODE_PRIVATE);
                        SharedPreferences.Editor edit = myshare.edit();
                        edit.putString("account",editAccount.getText().toString());
                        String encrypt = AESTool.encrypt(editPassword.getText().toString());
                        edit.putString("password",encrypt);
                        edit.putBoolean("rememberPs", true);
                        edit.apply();
                        runOnUiThread(()->{
                            DisplayUtil.displayToast(this,"登录成功并记住密码");
                            startActivity(intent);
                        });
                    }else {
                        // 删除登录状态
                        SharedPreferences myshare = getSharedPreferences("myshare", MODE_PRIVATE);
                        SharedPreferences.Editor edit = myshare.edit();
                        edit.putString("password","");
                        edit.putBoolean("rememberPs", false);
                        edit.apply();
                        runOnUiThread(()->{
                            DisplayUtil.displayToast(this,"登录成功");
                            startActivity(intent);
                        });
                    }
                }else {
                    runOnUiThread(()->{
                        DisplayUtil.displayToast(this,"登录失败，请检查账号密码是否错误");
                        initCode();  // 获取并显示新的验证码
                    });
                }
            }).start();
        });
        imageCode.setOnClickListener((view -> {
            initCode();  // 获取并显示新的验证码
        }));
        init(); // 获取本地存储的登录状态并初始化 UI 状态
    }
    private void init(){
        initCode();
        // 获取本地存储的登录状态
        SharedPreferences myshare = getSharedPreferences("myshare", MODE_PRIVATE);
        String account = myshare.getString("account", "");
        String password = myshare.getString("password", "");
        boolean rememberPs= myshare.getBoolean("rememberPs",false);
        editAccount.setText(account);
        if (!account.isEmpty() &&!password.isEmpty()){
            String decrypt = AESTool.decrypt(password);
            editPassword.setText(decrypt);
            checkBox.setChecked(rememberPs);
        }else {
            checkBox.setChecked(rememberPs);
        }
    }
    private void initCode(){
        new Thread(()->{
            MyHttpConnection httpConnection=new MyHttpConnection();
            String code = httpConnection.doGet("http://10.0.2.2:8080/captchaImage");
            CaptchaImageData imageData = JSONObject.parseObject(code, CaptchaImageData.class);
            EventBus.getDefault().post(new MessageEvent<>(imageData));
        }).start();


    }
    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent<CaptchaImageData> event) {
        CaptchaImageData data = event.getData();
        loginPost.setUuid(data.getUuid());
        String imgBase64 = data.getImg();
        if (imgBase64 != null) {
            Bitmap bitmap = Base64ToBitmapConverter.convert(imgBase64);
            imageCode.setImageBitmap(bitmap);
        }
    }
}